import React, { Component } from 'react'
// import ReactROM from 'react-dom'
import './Drum.css'

import CLAP from './assets/sounds/clap.wav'
import HITHAT from './assets/sounds/hihat.wav'
import BOOM from './assets/sounds/boom.wav'
import KICK from './assets/sounds/kick.wav'
import OPENHAT from './assets/sounds/openhat.wav'
import SNARE from './assets/sounds/snare.wav'
import TOM from './assets/sounds/tom.wav'
import TINK from './assets/sounds/tink.wav'
import RIDE from './assets/sounds/ride.wav'


export default class Drum extends Component {

  state = {
    currentCode: 0,
    info: [
    {keyLable: "A", code:"KeyA", name: "CLAP", src:CLAP},
    {keyLable: "S", code:"KeyS", name: "HIHAT", src:HITHAT},
    {keyLable: "D", code:"KeyD", name: "KICK", src:KICK},
    {keyLable: "F", code:"KeyF", name: "OPENHAT", src:OPENHAT},
    {keyLable: "G", code:"KeyG", name: "BOOM", src:BOOM},
    {keyLable: "H", code:"KeyH", name: "RIDE", src:RIDE},
    {keyLable: "J", code:"KeyJ", name: "SNARE", src:SNARE},
    {keyLable: "K", code:"KeyK", name: "TOM", src: TOM},
    {keyLable: "L", code:"KeyL", name: "TINK", src:TINK},
    ]
  }
  drumKeyElement = React.createRef()

  handleKeyDown(event){
    this.setState({currentCode: 0})
    const {info} = this.state

    info.map(item => {
      if (item.code === event.code) {
        this.setState({currentCode: event.code})
        const audioObj = new Audio(item.src)
        audioObj.play()
      }
    })
  } 

  handleTransitionEnd(event) {
    if (event.propertyName !== 'transform') return

    this.setState({ currentCode: 0 })
    this.drumKeyElement.current.classList.remove("playing")
  }

  componentDidMount(){
    document.addEventListener('keydown', (event)=>{ this.handleKeyDown(event) })
  }

  componentWillUnmount(){
    document.removeEventListener('keydown', (event)=>{ this.handleKeyDown(event) })
  }

  render(){
    const {info, currentCode} = this.state

    return (
        <div className="keys">
        {info.map( (v, idx) => {
          return (
              <div ref={this.drumKeyElement} onTransitionEnd={event => this.handleTransitionEnd(event)} className={currentCode===v.code? "key playing": "key"} key={idx}>
                <kbd>{v.keyLable}</kbd>
                <span className="sound">{v.name}</span>
              </div>
        )})}
        </div>
    )
  }
}